package org.jeecg.modules.lab.util.wordUtil;

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.List;

@Component
@Slf4j
public class WordToPdfUtils {


    /**
     * word转pdf
     *
     * @param file
     * @param pdfFile
     * @throws IOException
     */
    public void wordToPdf(String file, String pdfFile) throws IOException {
        /*转成pdf*/
        InputStream docxInputStream = null;
        OutputStream outputStream = null;
        try {
            // 原word地址
            docxInputStream = new FileInputStream(file);
            outputStream = new FileOutputStream(pdfFile);
            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream)
                    .as(DocumentType.DOCX)
                    .to(outputStream)
                    .as(DocumentType.PDF).execute();
            // 关闭
            converter.shutDown();
            // 关闭
            outputStream.close();
            // 关闭
            docxInputStream.close();
        } catch (Exception e) {
            System.out.println("[documents4J] word转pdf失败:" + e.toString());
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
            if (docxInputStream != null) {
                docxInputStream.close();
            }
        }
    }


    /**
     * 合成pdf
     *
     * @param listFile
     * @param params
     * @param reportNumber
     * @param samName
     */
    public void hcPdf(List<String> listFile, String params, String reportNumber, String samName) {
        String result = "D:/opt/upFiles/labPdf/" + samName + "-" + params + "-" + reportNumber + ".pdf";

        File pdffile = new File(result);
        if (!pdffile.exists()) {
            pdffile.delete();
        }
        PdfDocument pdfDoc = null;
        try {
            pdfDoc = new PdfDocument(new PdfWriter(result));
            for (String file : listFile) {
                PdfDocument sourcePdfDoc = new PdfDocument(new PdfReader(file));
                sourcePdfDoc.copyPagesTo(1, sourcePdfDoc.getNumberOfPages(), pdfDoc);
                sourcePdfDoc.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pdfDoc.close();
        }

    }
}
